<?
#This program is copyright by Andre Coetzee email: ac@main.me
#and is licensed under the GPL v3
#
#
#
#
#Please add yourself to: http://www.accounting-123.com
#Developers, Software Vendors, Support, Accountants, Users
#
#
#The full software license can be found here:
#http://www.accounting-123.com/a.php?a=153/GPLv3
#
#
#
#
#
#
#
#
#
#
#

# get settings
require("settings.php");
require("core-settings.php");
require("libs/ext.lib.php");

# decide what to do
if (isset($_GET["deptid"]) && isset($_GET["letters"])) {
	$OUTPUT = details($_GET);
}elseif (isset($_GET["sordid"]) && isset($_GET["cont"])) {
	$_GET["stkerr"] = '0,0';
	$OUTPUT = details($_GET);
}else{
	if (isset($_POST["key"])) {
		switch ($_POST["key"]) {
            case "details":
				$OUTPUT = details($_POST);
				break;
			case "update":
				$OUTPUT = write($_POST);
				break;
            default:
				$OUTPUT = view();
		}
	} else {
		$OUTPUT = view();
	}
}

# get templete
require("template.php");



# Default view
function view()
{

	# Query server for depts
	db_conn("exten");

	$sql = "SELECT * FROM departments WHERE div = '".USER_DIV."' ORDER BY deptname ASC";
	$deptRslt = db_exec ($sql) or errDie ("Unable to view customers");
	if (pg_numrows ($deptRslt) < 1) {
		return "<li class='err'>No Departments found in Cubit.</li>";
	}else{
		$depts = "<select name='deptid'>";
		while($dept = pg_fetch_array($deptRslt)){
			$depts .= "<option value='$dept[deptid]'>$dept[deptname]</option>";
		}
		$depts .= "</select>";
	}


	// Layout
	$view = "
		<br><br>
		<form action='".SELF."' method='POST' name='form'>
		<table ".TMPL_tblDflts." width='400'>
			<input type='hidden' name='key' value='details'>
			<input type='hidden' name='cussel' value='cussel'>
			<tr>
				<th colspan='2'>New International Sales Order</th>
			</tr>
			<tr bgcolor='".bgcolorg()."'>
				<td>Select Department</td>
				<td valign='center'>$depts</td>
			</tr>
			<tr bgcolor='".bgcolorg()."'>
				<td>First Letters of customer</td>
				<td valign='center'><input type='text' size='5' name='letters' maxlength='5'></td>
			</tr>
			<tr><td><br></td></tr>
			<tr>
				<td><input type='button' value='&laquo Cancel' onClick='javascript:history.back();'></td>
				<td valign='center'><input type='submit' value='Continue &raquo'></td>
			</tr>
		</table></form>
		<p>
		<table ".TMPL_tblDflts.">
			<tr>
				<th>Quick Links</th>
			</tr>
			<tr bgcolor='".bgcolorg()."'>
				<td><a href='sorder-view.php'>View Sales Orders</a></td>
			</tr>
			<tr bgcolor='".bgcolorg()."'>
				<td><a href='customers-new.php'>New Customer</a></td>
			</tr>
			<script>document.write(getQuicklinkSpecial());</script>
		</table>";
	return $view;

}



# Default view
function view_err($_POST, $err = "")
{

	# get vars
	extract ($_POST);

	# Query server for depts
	db_conn("exten");

	$sql = "SELECT * FROM departments WHERE div = '".USER_DIV."' ORDER BY deptname ASC";
	$deptRslt = db_exec ($sql) or errDie ("Unable to view customers");
	if (pg_numrows ($deptRslt) < 1) {
		return "<li class='err'>No Departments found in Cubit.</li>";
	}else{
		$depts = "<select name='deptid'>";
		while($dept = pg_fetch_array($deptRslt)){
			if(isset($deptid) && $dept['deptid'] == $deptid){
				$sel = "selected";
			}else{
				$sel = "";
			}
			$depts .= "<option value='$dept[deptid]' $sel>$dept[deptname]</option>";
		}
		$depts .= "</select>";
	}

	//layout
	$view = "
		<br><br>
		<form action='".SELF."' method='POST' name='form'>
		<table ".TMPL_tblDflts." width='400'>
			<input type='hidden' name='key' value='details'>
			<input type='hidden' name='cussel' value='cussel'>
			<tr>
				<th colspan='2'>New International Sales Order</th>
			</tr>
			<tr>
				<td colspan='2'>$err</td>
			</tr>
			<tr bgcolor='".bgcolorg()."'>
				<td>Select Department</td>
				<td valign='center'>$depts</td>
			</tr>
			<tr bgcolor='".bgcolorg()."'>
				<td>First Letters of customer</td>
				<td valign='center'><input type='text' size='5' name='letters' value='$letters' maxlength='5'></td>
			</tr>
			<tr><td><br></td></tr>
			<tr>
				<td><input type='button' value='&laquo Cancel' onClick='javascript:history.back();'></td>
				<td valign='center'><input type='submit' value='Continue &raquo'></td>
			</tr>
		</table>
		</form>
		<p>
		<table ".TMPL_tblDflts.">
			<tr>
				<th>Quick Links</th>
			</tr>
			<tr bgcolor='".bgcolorg()."'>
				<td><a href='sorder-view.php'>View Sales Orders</a></td>
			</tr>
			<tr bgcolor='".bgcolorg()."'>
				<td><a href='customers-new.php'>New Customer</a></td>
			</tr>
			<script>document.write(getQuicklinkSpecial());</script>
		</table>";
	return $view;

}



# create a dummy Sales Order
function create_dummy($deptid)
{

	db_connect();

	# Dummy Vars
	$cusnum = 0;
	$salespn = "";
	$comm = "";
	$salespn = "";
	$chrgvat = getSetting("SELAMT_VAT");
	$odate = date("Y-m-d");
	$ordno = "";
	$delchrg = "0.00";
	$cordno = "";
	$terms = 0;
	$traddisc = 0;
	$SUBTOT = 0;
	$vat = 0;
	$total = 0;

	$fcid = getDef_fcid();
	$curr = getSymbol($fcid);
	$xrate = getRate($fcid);

	// $sordid = divlastid ("sord", USER_DIV);

	# insert Sales Order to DB
	$sql = "
		INSERT INTO sorders (
			deptid, cusnum, cordno, ordno, chrgvat, fcid, currency, xrate, terms, 
			traddisc, salespn, odate, delchrg, subtot, vat, total, balance, comm, 
			username, location, accepted, done, div
		) VALUES (
			'$deptid', '$cusnum',  '$cordno', '$ordno', '$chrgvat', '$fcid', '$curr[symbol]', '$xrate', '$terms', 
			'$traddisc', '$salespn', '$odate', '$delchrg', '$SUBTOT', '$vat' , '$total', '$total', '$comm', 
			'".USER_NAME."', 'int', 'n', 'n', '".USER_DIV."'
		)";
	$rslt = db_exec($sql) or errDie("Unable to insert Sales Order to Cubit.",SELF);

	# get next ordnum
	$sordid = pglib_lastid ("sorders", "sordid");
	return $sordid;

}



# details
function details($_POST, $error="")
{

	# get vars
	extract ($_POST);

	# validate input
	require_lib("validate");

	$v = new  validate ();
	if(isset($sordid)){
		$v->isOk ($sordid, "num", 1, 20, "Invalid sales order number.");
	}else{
		$v->isOk ($deptid, "num", 1, 20, "Invalid department number.");
		$v->isOk ($letters, "string", 0, 5, "Invalid First 3 Letters.");
	}

	# display errors, if any
	if ($v->isError ()) {
		$errors = $v->getErrors();
		foreach ($errors as $e) {
			$error .= "<li class='err'>".$e["msg"]."</li>";
		}
		$confirm .= "$error<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
		return $confirm;
	}



	if(isset($deptid)){

		if ($deptid == "0"){
			$searchdept = "";
		}else {
			$searchdept = "deptid = '$deptid' AND ";
		}

		db_connect();

		# Query server for customer info
		$sql = "SELECT cusnum,cusname,surname FROM customers WHERE $searchdept location = 'int' AND lower(surname) LIKE lower('$letters%') AND blocked != 'yes' AND div = '".USER_DIV."' ORDER BY surname";
		$custRslt = db_exec ($sql) or errDie ("Unable to view customers");
		if (pg_numrows ($custRslt) < 1) {
			$err = "<li class='err'>No customer names starting with <b>$letters</b> in database.</li>";
			return view_err($_POST, $err);
		}
	}

	if(!isset($sordid)){
		$sordid = create_dummy($deptid);
		$stkerr = "0,0";
	}

	if(!isset($done)){
		$done = "";
	}

	# Get Sales Order info
	db_connect();

	$sql = "SELECT * FROM sorders WHERE sordid = '$sordid' AND div = '".USER_DIV."'";
	$sordRslt = db_exec ($sql) or errDie ("Unable to get Sales Order information");
	if (pg_numrows ($sordRslt) < 1) {
		return "<li class='err'>Sales Order Not Found</li>";
	}
	$sord = pg_fetch_array($sordRslt);

	# check if Sales Order has been printed
	if($sord['accepted'] == "y"){
		$error = "<li class='err'> Error : Sales Order number <b>$sordid</b> has already been printed.</li>";
		$error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
		return $error;
	}

	$currs = getSymbol($sord['fcid']);

	# get department
	db_conn("exten");

	$sql = "SELECT * FROM departments WHERE deptid = '$sord[deptid]' AND div = '".USER_DIV."'";
	$deptRslt = db_exec($sql);
	if(pg_numrows($deptRslt) < 1){
		$dept['deptname'] = "<li class='err'>Department not Found.</li>";
	}else{
		$dept = pg_fetch_array($deptRslt);
	}

	# Get selected customer info
	db_connect();

	$sql = "SELECT * FROM customers WHERE cusnum = '$sord[cusnum]' AND location = 'int' AND div = '".USER_DIV."'";
	$custRslt = db_exec ($sql) or errDie ("Unable to view customer");
	if (pg_numrows ($custRslt) < 1) {

		if ($deptid == "0"){
			$searchdept = "";
		}else {
			$searchdept = "deptid = '$sord[deptid]' AND ";
		}

		db_connect();

		# Query server for customer info
		$sql = "SELECT cusnum,cusname,surname FROM customers WHERE $searchdept location = 'int' AND lower(surname) LIKE lower('$letters%') AND div = '".USER_DIV."' ORDER BY surname";
		$custRslt = db_exec ($sql) or errDie ("Unable to view customers");
		if (pg_numrows ($custRslt) < 1) {
			$err = "<li class='err'>No customer names starting with <b>$letters</b> in database.</li>";
			return view_err($_POST, $err);
		}else{
			$customers = "<select name='cusnum' onChange='javascript:document.form.submit();'>";
			$customers .= "<option value='-S' selected>Select Customer</option>";
			while($cust = pg_fetch_array($custRslt)){
				$customers .= "<option value='$cust[cusnum]'>$cust[cusname] $cust[surname]</option>";
			}
			$customers .= "</select>";
		}
		# take care of the unset vars
		$cust['addr1'] = "";
		$cust['cusnum'] = "";
		$cust['vatnum'] = "";
		$cust['accno'] = "";
	}else{
		$cust = pg_fetch_array($custRslt);
		# moarn if customer account has been blocked
		if($cust['blocked'] == 'yes'){
			return "<li class='err'>Error : Selected customer account has been blocked.</li>";
		}
		$customers = "<input type='hidden' name='cusnum' value='$cust[cusnum]'>$cust[cusname]  $cust[surname]";
		$cusnum = $cust['cusnum'];
	}

/* --- Start Drop Downs --- */

	# Select warehouse
	db_conn("exten");

	$whs = "<select name='whidss[]' onChange='javascript:document.form.submit();'>";
	$sql = "SELECT * FROM warehouses WHERE div = '".USER_DIV."' ORDER BY whname ASC";
	$whRslt = db_exec($sql);
	if(pg_numrows($whRslt) < 1){
		return "<li class='err'> There are no Stores found in Cubit.</li>";
	}else{
		$whs .= "<option value='-S' disabled selected>Select Store</option>";
		while($wh = pg_fetch_array($whRslt)){
			$whs .= "<option value='$wh[whid]'>($wh[whno]) $wh[whname]</option>";
		}
	}
	$whs .= "</select>";

	# get sales people
	db_conn("exten");

	$sql = "SELECT * FROM salespeople WHERE div = '".USER_DIV."' ORDER BY salesp ASC";
	$salespRslt = db_exec ($sql) or errDie ("Unable to get sales people.");
	if (pg_numrows ($salespRslt) < 1) {
		return "<li class='err'> There are no Sales People found in Cubit.</li>";
	}else{
		$salesps = "<select name='salespn'>";
		while($salesp = pg_fetch_array($salespRslt)){
			if($salesp['salesp'] == $sord['salespn']){
				$sel = "selected";
			}else{
				$sel = "";
			}
			$salesps .= "<option value='$salesp[salesp]' $sel>$salesp[salesp]</option>";
		}
		$salesps .= "</select>";
	}

	# days drop downs
	$days = array("0"=>"0","7"=>"7","14"=>"14","30"=>"30","60"=>"60","90"=>"90","120"=>"120");
	$termssel = extlib_cpsel("terms", $days, $sord['terms']);

	# Keep the charge vat option stable
	if($sord['chrgvat'] == "inc"){
		$chin = "checked=yes";
		$chex = "";
		$chno = "";
	}elseif($sord['chrgvat'] == "exc"){
		$chin = "";
		$chex = "checked=yes";
		$chno = "";
	}else{
		$chin = "";
		$chex = "";
		$chno = "checked=yes";
	}

	# format date
	list($isord_year, $isord_month, $isord_day) = explode("-", $sord['odate']);

/* --- End Drop Downs --- */

/* --- Start Products Display --- */

	# select all products
	$products = "
		<table ".TMPL_tblDflts." width='100%'>
			<tr>
				<th>STORE</th>
				<th>ITEM NUMBER</th>
				<th>DESCRIPTION</th>
				<th>QTY</th>
				<th colspan='2'>UNIT PRICE</th>
				<th>UNIT DISCOUNT</th>
				<th>AMOUNT</th>
				<th>Remove</th>
			<tr>";

	# get selected stock in this Sales Order
	db_connect();

	$sql = "SELECT * FROM sorders_items  WHERE sordid = '$sordid' AND div = '".USER_DIV."'";
	$stkdRslt = db_exec($sql);
	$i = 0;
	$key = 0;
	while($stkd = pg_fetch_array($stkdRslt)){

		# keep track of selected stock amounts
		$amts[$i] = $stkd['amt'];
		$i++;

		# get warehouse name
		db_conn("exten");

		$sql = "SELECT whname FROM warehouses WHERE whid = '$stkd[whid]' AND div = '".USER_DIV."'";
		$whRslt = db_exec($sql);
		$wh = pg_fetch_array($whRslt);

		# get selected stock in this warehouse
		db_connect();

		$sql = "SELECT * FROM stock WHERE stkid = '$stkd[stkid]' AND div = '".USER_DIV."'";
		$stkRslt = db_exec($sql);
		$stk = pg_fetch_array($stkRslt);

		# put in product
		$products .= "
			<tr bgcolor='".bgcolorg()."'>
				<td><input type='hidden' name='whids[]' value='$stkd[whid]'>$wh[whname]</td>
				<td>
					<input type='hidden' name='stkids[]' value='$stkd[stkid]'>
					<a href='#' onclick='openwindow(\"stock-amt-det.php?stkid=$stk[stkid]\")'>$stk[stkcod]</a>
				</td>
				<td>".extlib_rstr($stk['stkdes'], 30)."</td>
				<td><input type='text' size='3' name='qtys[]' value='$stkd[qty]'></td>
				<td>".CUR." <input type='text' size='8' name='unitcost[]' value='$stkd[funitcost]'></td>
				<td>$sord[currency] <input type='text' size='8' name='cunitcost[]' value='$stkd[unitcost]'></td>
				<td>".CUR."  <input type='text' size='4' name='disc[]' value='$stkd[disc]'> OR <input type='text' size='4' name='discp[]' value='$stkd[discp]' maxlength='5'>%</td>
				<td><input type='hidden' name='amt[]' value='$stkd[amt]'> $sord[currency] $stkd[amt]</td>
				<td><input type='checkbox' name='remprod[]' value='$key'><input type='hidden' name='SCROLL' value='yes'></td>
			</tr>";
		$key++;
	}

	# Look above(remprod keys)
	$keyy = $key;

	# look above(if i = 0 then there are no products)
	if($i == 0){
		$done = "";
	}

	# check if stock warehouse was selected
	if(isset($whidss)){
		foreach($whidss as $key => $whid){
			if(isset($stkidss[$key]) && $stkidss[$key] != "-S" && isset($cust['pricelist'])){
				# skip if not selected
				if($whid == "-S"){
					continue;
				}

				# get selected warehouse name
				db_conn("exten");

				$sql = "SELECT whname FROM warehouses WHERE whid = '$whid' AND div = '".USER_DIV."'";
				$whRslt = db_exec($sql);
				$wh = pg_fetch_array($whRslt);

				# get selected stock in this warehouse
				db_connect();

				$sql = "SELECT * FROM stock WHERE stkid = '$stkidss[$key]' AND div = '".USER_DIV."' ORDER BY stkcod ASC";
				$stkRslt = db_exec($sql);
				$stk = pg_fetch_array($stkRslt);

				# get price from price list if it is set
				if(isset($cust['pricelist'])){
					# get selected stock in this warehouse
					db_conn("exten");
					$sql = "SELECT price FROM plist_prices WHERE listid = '$cust[pricelist]' AND stkid = '$stk[stkid]' AND div = '".USER_DIV."'";
					$plRslt = db_exec($sql);
					if(pg_numrows($plRslt) > 0){
						$pl = pg_fetch_array($plRslt);
						$stk['selamt'] = $pl['price'];
					}
				}

				/* -- Start Some Checks -- */
				# check if they are selling too much
				if(($stk['units'] - $stk['alloc']) < $qtyss[$key]){
					if(!in_array($stk['stkid'], explode(",", $stkerr))){
						if($stk['type'] != 'lab'){
							$stkerr .= ",$stk[stkid]";
							$error .= "<li class='err'>Warning :  Item number <b>$stk[stkcod]</b> does not have enough items available.</li>";
						}
					}
				}
				/* -- End Some Checks -- */

				# Calculate the Discount discount
				if($discs[$key] < 1){
					if($discps[$key] > 0){
						$discs[$key] = round((($discps[$key]/100) * $stk['selamt']), 2);
					}
				}else{
					$discps[$key] = round((($discs[$key] * 100) / $stk['selamt']), 2);
				}

				# Calculate amount
				$amt[$key] = ($qtyss[$key] * ($stk['selamt'] - $discs[$key]));

				$stkd['cselamt'] = sprint($stkd['selamt']/$sord['xrate']);

				# put in selected warehouse and stock
				$products .= "
					<tr bgcolor='".bgcolorg()."'>
						<td><input type='hidden' name='whids[]' value='$whid'>$wh[whname]</td>
						<td><input type='hidden' name='stkids[]' value='$stk[stkid]'><a href='#' onclick='openwindow(\"stock-amt-det.php?stkid=$stk[stkid]\")'>$stk[stkcod]</a></td>
						<td>".extlib_rstr($stk['stkdes'], 30)."</td>
						<td><input type='text' size='3' name='qtys[]' value='$qtyss[$key]'></td>
						<td><input type='text' size='8' name='unitcost[]'  value='$stk[selamt]'></td>
						<td>$sord[currency] <input type='text' size='8' name='cunitcost[]' value='$stkd[cselamt]'></td>
						<td>".CUR."  <input type='text' size='4' name='disc[]' value='$discs[$key]'> OR <input type='text' size='4' name='discp[]' value='$discps[$key]' maxlength='5'>%</td>
						<td><input type='hidden' name='amt[]' value='$amt[$key]'> $sord[currency] $amt[$key]</td>
						<td><input type='checkbox' name='remprod[]' value='$keyy'></td>
					</tr>";
				$keyy++;
			}else{
				if(!isset($diffwhBtn)){
					# skip if not selected
					if($whid == "-S"){
						continue;
					}

					# get warehouse name
					db_conn("exten");

					$sql = "SELECT whname FROM warehouses WHERE whid = '$whid' AND div = '".USER_DIV."'";
					$whRslt = db_exec($sql);
					$wh = pg_fetch_array($whRslt);

					# get stock on this warehouse
					db_connect();
					$sql = "SELECT * FROM stock WHERE whid = '$whid' AND blocked = 'n' AND div = '".USER_DIV."' ORDER BY stkcod ASC";
					$stkRslt = db_exec ($sql) or errDie ("Unable to retrieve stocks from database.");
					if (pg_numrows ($stkRslt) < 1) {
						$error .= "<li class='err'>There are no stock items in the selected store.</li>";
						continue;
					}
					$stks = "<select class='width:15' name='stkidss[]' onChange='javascript:document.form.submit();'>";
					$stks .= "<option value='-S' disabled selected>Select Number</option>";
					$count = 0;
					while($stk = pg_fetch_array($stkRslt)){
						$stks .= "<option value='$stk[stkid]'>$stk[stkcod] (".sprint3($stk['units'] - $stk['alloc']).")</option>";
					}
					$stks .= "</select> ";

					# put in drop down and warehouse
					$products .= "
						<tr bgcolor='".bgcolorg()."'>
							<td><input type='hidden' name='whidss[]' value='$whid'>$wh[whname]</td>
							<td>$stks</td>
							<td> </td>
							<td><input type='text' size='3' name='qtyss[]'  value='1'></td>
							<td> </td>
							<td> </td>
							<td>".CUR."  <input type='text' size='4' name='discs[]' value='0'> OR <input type='text' size='4' name='discps[]' value='0' maxlength='5'>%</td>
							<td><input type='hidden' name='amts[]' value='0.00'>$sord[currency] 0.00</td>
							<td></td>
						</tr>";
				}
			}
		}
	}else{
		if(!isset($diffwhBtn)){
			# check if setting exists
			db_connect();
			$sql = "SELECT value FROM set WHERE label = 'DEF_WH' AND div = '".USER_DIV."'";
			$Rslt = db_exec ($sql) or errDie ("Unable to check database for existing settings.");
			if (pg_numrows ($Rslt) > 0) {
				$set = pg_fetch_array($Rslt);
				$whid = $set['value'];
				if(isset($wtd)){$whid = $wtd;}
				# get selected warehouse name
				db_conn("exten");

				$sql = "SELECT whname FROM warehouses WHERE whid = '$whid' AND div = '".USER_DIV."'";
				$whRslt = db_exec($sql);
				$wh = pg_fetch_array($whRslt);

				# get stock on this warehouse
				db_connect();

				$sql = "SELECT * FROM stock WHERE whid = '$whid' AND blocked = 'n' AND div = '".USER_DIV."' ORDER BY stkcod ASC";
				$stkRslt = db_exec ($sql) or errDie ("Unable to retrieve stocks from database.");
				if (pg_numrows ($stkRslt) < 1) {
					if(!(isset($err))) {$err="";}
					$err .= "<li>There are no stock items in the selected warehouse.</li>";
				}
				$stks = "<select class='width:15' name='stkidss[]' onChange='javascript:document.form.submit();'>";
				$stks .= "<option value='-S' disabled selected>Select Number</option>";
				$count = 0;
				while($stk = pg_fetch_array($stkRslt)){
					$stks .= "<option value='$stk[stkid]'>$stk[stkcod] (".sprint3($stk['units'] - $stk['alloc']).")</option>";
				}
				$stks .= "</select> ";
				$products .= "
					<tr bgcolor='".bgcolorg()."'>
						<td><input type='hidden' name='whidss[]' value='$whid'>$wh[whname]</td>
						<td>$stks</td>
						<td> </td>
						<td><input type='text' size='3' name='qtyss[]' value='1'></td>
						<td> </td>
						<td> </td>
						<td>".CUR."  <input type='text' size='4' name='discs[]' value='0'> OR <input type='text' size='4' name='discps[]' value='0' maxlength='5'>%</td>
						<td>$sord[currency] 0.00</td>
						<td></td>
					</tr>";
			}else{
				$products .= "
					<tr bgcolor='".bgcolorg()."'>
						<td>$whs</td>
						<td></td>
						<td> </td>
						<td> </td>
						<td> </td>
						<td> </td>
						<td>".CUR."  <input type='text' size='4' name='discs[]' value='0'> OR <input type='text' size='4' name='discps[]' value='0' maxlength='5'>%</td>
						<td>$sord[currency] 0.00</td>
						<td></td>
					</tr>";
			}
		}
	}

	/* -- start Listeners -- */

	if(isset($diffwhBtn)){
		$products .= "
			<tr bgcolor='".bgcolorg()."'>
				<td>$whs</td>
				<td></td>
				<td> </td>
				<td> </td>
				<td> </td>
				<td> </td>
				<td>".CUR."  <input type='text' size='4' name='discs[]' value='0'> OR <input type='text' size='4' name='discps[]' value='0' maxlength='5'>%</td>
				<td>$sord[currency] 0.00</td>
				<td></td>
			</tr>";
	}

	/* -- End Listeners -- */

	$products .= "</table>";

/* --- End Products Display --- */


/* --- Start Some calculations --- */

	# Calculate subtotal
	$SUBTOT = sprint($sord['subtot']);
	$VATP = TAX_VAT;

	# Calculate subtotal
	$SUBTOT = sprint($sord['subtot']);
 	$VAT = sprint($sord['vat']);
	$TOTAL = sprint($sord['total']);

/* --- End Some calculations --- */

/*--- Start checks --- */
	# check only if the customer is selected
	if(isset($cusnum) && $cusnum != "-S"){
		#check againg credit limit
		if(($TOTAL + $cust['balance']) > $cust['credlimit']){
			$error .= "<li class='err'>Warning : Customers Credit limit of <b>$sord[currency] $cust[credlimit]</b> has been exceeded.</li>";
		}
		$avcred = ($cust['credlimit'] - $cust['balance']);
	}else{
		$avcred = "0.00";
	}
/*--- Start checks --- */

	if(!(isset($letters))){$letters="";}

/* -- Final Layout -- */
	$details = "
		<center>
		<h3>New International Sales Order</h3>
		<form action='".SELF."' method='POST' name='form'>
			<input type='hidden' name='key' value='update'>
			<input type='hidden' name='sordid' value='$sordid'>
			<input type='hidden' name='letters' value='$letters'>
			<input type='hidden' name='stkerr' value='$stkerr'>
		<table ".TMPL_tblDflts." width='95%'>
		 	<tr>
		 		<td valign='top'>
					<table ".TMPL_tblDflts.">
						<tr>
							<th colspan='2'> Customer Details </th>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<td>Department</td>
							<td valign='center'>$dept[deptname]</td>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<td>Account No.</td>
							<td valign='center'>$cust[accno]</td>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<td>Customer</td>
							<td valign='center'>$customers</td>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<td valign='top'>Customer Address</td>
							<td valign='center'>".nl2br($cust['addr1'])."</td>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<td>Customer Order number</td>
							<td valign='center'><input type='text' size='10' name='cordno' value='$sord[cordno]'></td>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<td>Customer Vat Number</td>
							<td>$cust[vatnum]</td>
						</tr>
					</table>
				</td>
				<td valign='top' align='right'>
					<table ".TMPL_tblDflts.">
						<tr>
							<th colspan='2'> Sales Order Details </th>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<td>Sales Order No.</td>
							<td valign='center'>$sord[sordid]</td>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<td>Order No.</td>
							<td valign='center'><input type='text' size='5' name='ordno' value='$sord[ordno]'></td>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<td>VAT Inclusive</td>
							<td valign='center'>
								Yes <input type='radio' size='7' name='chrgvat' value='inc' $chin> 
								No <input type='radio' size='7' name='chrgvat' value='exc' $chex> 
								No Vat<input type='radio' size='7' name='chrgvat' value='nov' $chno>
							</td>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<td>Foreign Currency</td>
							<td valign='center'>$currs[symbol] - $currs[name] &nbsp;&nbsp;Exchange rate ".CUR." <input type='text' size='7' name='xrate' value='$sord[xrate]'></td>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<td>Terms</td>
							<td valign='center'>$termssel Days</td>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<td>Sales Person</td>
							<td valign='center'>$salesps</td>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<td>Sales Order Date</td>
							<td valign='center'>".mkDateSelect("isord",$isord_year,$isord_month,$isord_day)."</td>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<td>Available Credit</td>
							<td>$sord[currency] ".sprint($avcred)."</td>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<td>Trade Discount</td>
							<td valign='center'><input type='text' size='5' name='traddisc' value='$sord[traddisc]'>%</td>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<td>Delivery Charge</td>
							<td valign='center'><input type='text' size='7' name='delchrg' value='$sord[delchrg]'></td>
						</tr>
					</table>
				</td>
			</tr>
			<tr><td><br></td></tr>
			<tr>
				<td colspan='2'>$products</td>
			</tr>
			<tr>
				<td>
					<p>
					<table ".TMPL_tblDflts.">
						<tr>
							<th width='25%'>Quick Links</th>
							<th width='25%'>Comments</th>
							<td rowspan='5' valign='top' width='50%'>$error</td>
						</tr>
						<tr>
							<td bgcolor='".bgcolorg()."'><a href='sorder-new.php'>New Sales Order</a></td>
							<td bgcolor='".bgcolorg()."' rowspan='4' align='center' valign='top'><textarea name='comm' rows='4' cols='20'>$sord[comm]</textarea></td>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<td><a href='sorder-view.php'>View Sales Orders</a></td>
						</tr>
						<script>document.write(getQuicklinkSpecial());</script>
					</table>
				</td>
				<td align='right'>
					<table ".TMPL_tblDflts." width='80%'>
						<tr bgcolor='".bgcolorg()."'>
							<td>SUBTOTAL</td>
							<td align='right'>$sord[currency] <input type='hidden' name='SUBTOT' value='$SUBTOT'>$SUBTOT</td>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<td>Trade Discount</td>
							<td align='right'>$sord[currency] $sord[discount]</td>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<td>Delivery Charge</td>
							<td align='right'>$sord[currency] $sord[delivery]</td>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<td><b>VAT @ $VATP%</b></td>
							<td align='right'>$sord[currency] $VAT</td>
						</tr>
						<tr bgcolor='".bgcolorg()."'>
							<th>GRAND TOTAL</th>
							<td align='right'>$sord[currency] $TOTAL</td>
						</tr>
					</table>
				</td>
			</tr>
			<tr>
				<td align='right'>
					<input type='submit' name='Cancel' value='Cancel'> | 
					<input name='diffwhBtn' type='submit' value='Different Store'> | 
					<input name='addprodBtn' type='submit' value='Add Product'> | 
					<input type='submit' name='saveBtn' value='Save'>
				</td>
				<td> | <input type='submit' name='upBtn' value='Update'>$done</td>
			</tr>
		</table>
		</form>
		</center>";
	return $details;
}



# write
function write($_POST)
{

	#get vars
	extract ($_POST);

	if(isset($Cancel)){
		db_connect();
		$Sl = "DELETE FROM sorders WHERE sordid='$sordid' AND cusnum=0 AND div = '".USER_DIV."'";
		$Rs = db_exec($Sl) or errDie ("Unable to delete Sales Order information");
		$sordid--;
		$Sql = "SELECT setval('sorders_sordid_seq', '$sordid')";
		$Rslt = db_exec ($Sql) or errDie ("Unable to set salesorder id.");
		header ("Location: main.php");
	}

	# validate input
	require_lib("validate");

	$v = new  validate ();
	$v->isOk ($cusnum, "num", 1, 20, "Invalid Customer, Please select a customer.");
	$v->isOk ($sordid, "num", 1, 20, "Invalid Sales Order Number.");
	$v->isOk ($cordno, "string", 0, 20, "Invalid Customer Order Number.");
	$v->isOk ($comm, "string", 0, 255, "Invalid Comments.");
	$v->isOk ($ordno, "num", 0, 20, "Invalid order number.");
	$v->isOk ($chrgvat, "string", 1, 4, "Invalid charge vat option.");
	$v->isOk ($terms, "num", 1, 20, "Invalid terms.");
	$v->isOk ($salespn, "string", 1, 255, "Invalid sales person.");
	$v->isOk ($isord_day, "num", 1, 2, "Invalid Sales Order Date day.");
	$v->isOk ($isord_month, "num", 1, 2, "Invalid Sales Order Date month.");
	$v->isOk ($isord_year, "num", 1, 5, "Invalid Sales Order Date year.");
	$odate = $isord_year."-".$isord_month."-".$isord_day;
	if(!checkdate($isord_month, $isord_day, $isord_year)){
		$v->isOk ($odate, "num", 1, 1, "Invalid Sales Order Date.");
	}
	$v->isOk ($traddisc, "float", 0, 20, "Invalid Trade Discount.");
	if($traddisc > 100){
		$v->isOk ($traddisc, "float", 0, 0, "Error : Trade Discount cannot be more than 100 %.");
	}
	$v->isOk ($delchrg, "float", 0, 20, "Invalid Delivery Charge.");
	$v->isOk ($SUBTOT, "float", 0, 20, "Invalid Delivery Charge.");

	# used to generate errors
	$error = "asa@";

	# check quantities
	if(isset($qtys)){
		foreach($qtys as $keys => $qty){
			$discp[$keys] += 0;
			$disc[$keys] += 0;

			$v->isOk ($qty, "float", 1, 16, "Invalid Quantity for product number : <b>".($keys+1)."</b>");
			$v->isOk ($disc[$keys], "float", 0, 20, "Invalid Discount for product number : <b>".($keys+1)."</b>.");
			if($disc[$keys] > $unitcost[$keys]){
				$v->isOk ($disc[$keys], "float", 0, 0, "Error : Discount for product number : <b>".($keys+1)."</b> is more than the unitcost.");
			}
			$v->isOk ($discp[$keys], "float", 0, 20, "Invalid Discount Percentage for product number : <b>".($keys+1)."</b>.");
			if($discp[$keys] > 100){
				$v->isOk ($discp[$keys], "float", 0, 0, "Error : Discount for product number : <b>".($keys+1)."</b> is more than 100 %.");
			}
			$unitcost[$keys] += 0;
			$cunitcost[$keys] += 0;
			$v->isOk ($unitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>".($keys+1)."</b>.");
			$v->isOk ($cunitcost[$keys], "float", 1, 20, "Invalid Unit Price for product number : <b>".($keys+1)."</b>.");
			if($qty < 1){
				$v->isOk ($qty, "num", 0, 0, "Error : Item Quantity must be at least one. Product number : <b>".($keys+1)."</b>");
			}
		}
	}
	# check whids
	if(isset($whids)){
		foreach($whids as $keys => $whid){
			$v->isOk ($whid, "num", 1, 10, "Invalid Store number, please enter all details.");
		}
	}

	# check stkids
	if(isset($stkids)){
		foreach($stkids as $keys => $stkid){
			$v->isOk ($stkid, "num", 1, 10, "Invalid Stock number, please enter all details.");
		}
	}
	# check amt
	if(isset($amt)){
		foreach($amt as $keys => $amount){
			$v->isOk ($amount, "float", 1, 20, "Invalid Amount, please enter all details.");
		}
	}

	# display errors, if any
	$err = "";
	if ($v->isError ()) {
		$errors = $v->getErrors();
			foreach ($errors as $e) {
			$err .= "<li class='err'>".$e["msg"]."</li>";
		}
		return details($_POST, $err);
	}



	# Get Sales Order info
	db_connect();

	$sql = "SELECT * FROM sorders WHERE sordid = '$sordid' AND div = '".USER_DIV."'";
	$sordRslt = db_exec ($sql) or errDie ("Unable to get Sales Order information");
	if (pg_numrows ($sordRslt) < 1) {
		return "<li>- Sales Order Not Found</li>";
	}
	$sord = pg_fetch_array($sordRslt);

	# check if Sales Order has been printed
	if($sord['accepted'] == "y"){
		$error = "<li class='err'> Error : Sales Order number <b>$sordid</b> has already been printed.</li>";
		$error .= "<p><input type='button' onClick='JavaScript:history.back();' value='&laquo; Correct submission'>";
		return $error;
	}

	# Get selected customer info
	db_connect();

	$sql = "SELECT * FROM customers WHERE cusnum = '$cusnum' AND div = '".USER_DIV."'";
	$custRslt = db_exec ($sql) or errDie ("Unable to get customer information");
	if (pg_numrows ($custRslt) < 1) {
		$sql = "SELECT * FROM sord_data WHERE sordid = '$sordid' AND div = '".USER_DIV."'";
		$custRslt = db_exec ($sql) or errDie ("Unable to get customer information data");
		$cust = pg_fetch_array($custRslt);
		$cust['cusname'] = $cust['customer'];
		$cust['surname'] = "";
		$cust['addr1'] = "";
		# currency
		$currs = getSymbol($cust['fcid']);
	}else{
		$cust = pg_fetch_array($custRslt);

		$sord['deptid'] = $cust['deptid'];

		# If customer was just selected, get the following
		if($sord['cusnum'] != $cusnum){
			$traddisc = $cust['traddisc'];
			$terms = $cust['credterm'];
			$xrate = getRate($cust['fcid']);
		}
		# currency
		$currs = getSymbol($cust['fcid']);
	}

	# get department
	db_conn("exten");

	$sql = "SELECT * FROM departments WHERE deptid = '$sord[deptid]' AND div = '".USER_DIV."'";
	$deptRslt = db_exec($sql);
	if(pg_numrows($deptRslt) < 1){
		$dept['deptname'] = "<i class='err'>Not Found</i>";
	}else{
		$dept = pg_fetch_array($deptRslt);
	}

	# fix those nasty zeros
	$xrate += 0;
	if($xrate == 0) $xrate = 1;
	$traddisc += 0;
	$delchrg += 0;

	# insert Sales Order to DB
	db_connect();

# begin updating
pglib_transaction ("BEGIN") or errDie("Unable to start a database transaction.",SELF);

	/* -- Start remove old items -- */
	# get selected stock in this Sales Order
	db_connect();
	$sql = "SELECT * FROM sorders_items  WHERE sordid = '$sordid' AND div = '".USER_DIV."'";
	$stktRslt = db_exec($sql);


	while($stkt = pg_fetch_array($stktRslt)){
		# update stock(alloc + qty)
		$sql = "UPDATE stock SET alloc = (alloc - '$stkt[qty]')  WHERE stkid = '$stkt[stkid]' AND div = '".USER_DIV."'";
		$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
	}


	# remove old items
	$sql = "DELETE FROM sorders_items WHERE sordid='$sordid' AND div = '".USER_DIV."'";
	$rslt = db_exec($sql) or errDie("Unable to update Sales Order items in Cubit.",SELF);
	/* -- End remove old items -- */

	$taxex = 0;
	if(isset($qtys)){
		foreach($qtys as $keys => $value){
			if(isset($remprod)){
				if(in_array($keys, $remprod)){
					# skip product (wonder if $keys still align)
					$amt[$keys] = 0;
					continue;
				}else{
					# get selamt from selected stock
					$sql = "SELECT * FROM stock WHERE stkid = '$stkids[$keys]' AND div = '".USER_DIV."'";
					$stkRslt = db_exec($sql);
					$stk = pg_fetch_array($stkRslt);

					# Calculate the unitcost
					if($cunitcost[$keys] > 0 && $unitcost[$keys] == 0){
						$unitcost[$keys] = ($cunitcost[$keys] * $xrate);
					}else{
						$cunitcost[$keys] = ($unitcost[$keys]/$xrate);
					}

					# Calculate amount
					$funitcost[$keys] = $unitcost[$keys];
					$famt[$keys] = ($qtys[$keys] * ($funitcost[$keys] - $disc[$keys]));

					# Calculate amount
					// $amt[$keys] = ($qtys[$keys] * ($unitcost[$keys] - $disc[$keys]));
					$unitcost[$keys] = sprint($funitcost[$keys]/$xrate);
					$amt[$keys] = sprint($famt[$keys]/$xrate);


					# Check Tax Excempt
					if($stk['exvat'] == 'yes'){
						$taxex += $amt[$keys];
					}

					$wtd = $whids[$keys];
					# insert Sales Order items
					$sql = "
						INSERT INTO sorders_items (
							sordid, whid, stkid, qty, unitcost, 
							funitcost, amt, famt, disc, discp, 
							div
						) VALUES (
							'$sordid', '$whids[$keys]', '$stkids[$keys]', '$qtys[$keys]', '$unitcost[$keys]', 
							'$funitcost[$keys]', '$amt[$keys]', '$famt[$keys]', '$disc[$keys]', '$discp[$keys]', 
							'".USER_DIV."'
						)";
					$rslt = db_exec($sql) or errDie("Unable to insert Sales Order items to Cubit.",SELF);

					# update stock(alloc + qty)
					$sql = "UPDATE stock SET alloc = (alloc + '$qtys[$keys]') WHERE stkid = '$stkids[$keys]' AND div = '".USER_DIV."'";
					$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
				}
			}else{
				# get selamt from selected stock
				$sql = "SELECT * FROM stock WHERE stkid = '$stkids[$keys]' AND div = '".USER_DIV."'";
				$stkRslt = db_exec($sql);
				$stk = pg_fetch_array($stkRslt);

				# Calculate the unitcost
				if($cunitcost[$keys] > 0 && $unitcost[$keys] == 0){
					$unitcost[$keys] = ($cunitcost[$keys] * $xrate);
				}else{
					$cunitcost[$keys] = ($unitcost[$keys]/$xrate);
				}

				# Calculate the Discount discount
				if($disc[$keys] < 1){
					if($discp[$keys] > 0){
						$disc[$keys] = (($discp[$keys]/100) * $unitcost[$keys]);
					}
				}else{
					$discp[$keys] = (($disc[$keys] * 100) / $unitcost[$keys]);
				}

				# Calculate amount
				$funitcost[$keys] = $unitcost[$keys];
				$famt[$keys] = ($qtys[$keys] * ($funitcost[$keys] - $disc[$keys]));

				# Calculate amount
				// $amt[$keys] = ($qtys[$keys] * ($unitcost[$keys] - $disc[$keys]));
				$unitcost[$keys] = sprint($funitcost[$keys]/$xrate);
				$amt[$keys] = sprint($famt[$keys]/$xrate);


				# Check Tax Excempt
				if($stk['exvat'] == 'yes'){
					$taxex += $amt[$keys];
				}

				$wtd = $whids[$keys];

				# insert Sales Order items
				$sql = "
					INSERT INTO sorders_items (
						sordid, whid, stkid, qty, unitcost, 
						funitcost, amt, famt, disc, discp, 
						div
					) VALUES (
						'$sordid', '$whids[$keys]', '$stkids[$keys]', '$qtys[$keys]', '$unitcost[$keys]', 
						'$funitcost[$keys]', '$amt[$keys]', '$famt[$keys]', '$disc[$keys]', '$discp[$keys]', 
						'".USER_DIV."'
					)";
				$rslt = db_exec($sql) or errDie("Unable to insert Sales Order items to Cubit.",SELF);

				# update stock(alloc + qty)
				$sql = "UPDATE stock SET alloc = (alloc + '$qtys[$keys]') WHERE stkid = '$stkids[$keys]' AND div = '".USER_DIV."'";
				$rslt = db_exec($sql) or errDie("Unable to update stock to Cubit.",SELF);
			}
			# everything is set place done button
			$_POST["done"] = " | <input name='doneBtn' type='submit' value='Done'>";
		}
	}else{
		$_POST["done"] = "";
	}

	/* --- ----------- Clac --------------------- */
	##----------------------NEW----------------------

	$sub = 0.00;
	if(isset($amt)) {
		$sub = sprint(array_sum($amt));
	}

	$VATP = TAX_VAT;

	if($chrgvat == "exc"){
		$taxex = sprint($taxex - ($taxex * $traddisc / 100));
		$subtotal = sprint($sub + $delchrg);
		$traddiscmt = sprint($subtotal * $traddisc/100);
		$subtotal = sprint($subtotal - $traddiscmt);
		$VAT = sprint(($subtotal - $taxex) * $VATP / 100);
		$SUBTOT = $sub;
		$TOTAL = sprint($subtotal + $VAT);
		$delexvat = sprint($delchrg);
	}elseif($chrgvat == "inc"){
		$ot = $taxex;
		$taxex = sprint($taxex - ($taxex * $traddisc / 100));
		$subtotal = sprint($sub + $delchrg);
		$traddiscmt = sprint($subtotal * $traddisc / 100);
		$subtotal = sprint($subtotal - $traddiscmt);
		$VAT = sprint(($subtotal - $taxex) * $VATP / (100 + $VATP));
		$SUBTOT = sprint($sub);
		$TOTAL = sprint($subtotal);
		$delexvat = sprint(($delchrg));
		$traddiscmt = sprint($traddiscmt);

	} else {
		$subtotal = sprint($sub + $delchrg);
		$traddiscmt = sprint($subtotal * $traddisc / 100);
		$subtotal = sprint($subtotal - $traddiscmt);
		$VAT = sprint(0);
		$SUBTOT = $sub;
		$TOTAL = $subtotal;
		$delexvat = sprint($delchrg);
	}

	/* --- ----------- Clac --------------------- */
	##----------------------END----------------------

/* --- ----------- Clac ---------------------

	# calculate subtot
	$SUBTOT = 0.00;
	if(isset($amt))
		$SUBTOT = array_sum($amt);

	$SUBTOT -= $taxex;

	# duplicate
	$SUBTOTAL = $SUBTOT;

	$VATP = TAX_VAT;
	if($chrgvat == "exc"){
		$SUBTOTAL = $SUBTOTAL;
		$delexvat= ($delchrg);
	}elseif($chrgvat == "inc"){
		$SUBTOTAL = sprint(($SUBTOTAL * 100)/(100 + $VATP));
		$delexvat = sprint(($delchrg * 100)/($VATP + 100));
	}else{
		$SUBTOTAL = ($SUBTOTAL);
		$delexvat = ($delchrg);
	}

	$SUBTOT = $SUBTOTAL;
	$EXVATTOT = $SUBTOT;
	$EXVATTOT += $delexvat;

	# Minus trade discount from taxex
	if($traddisc > 0){
		$traddiscmtt = (($traddisc/100) * $taxex);
	}else{
		$traddiscmtt = 0;
	}
	$taxext = ($taxex - $traddiscmtt);

	if($traddisc > 0) {
		$traddiscmt = ($EXVATTOT * ($traddisc/100));
	}else{
		$traddiscmt = 0;
	}
	$EXVATTOT -= $traddiscmt;
	// $EXVATTOT -= $taxex;

	$traddiscmt = sprint($traddiscmt  + $traddiscmtt);

	if($chrgvat != "nov"){
		$VAT = sprint($EXVATTOT * ($VATP/100));
	}else{
		$VAT = 0;
	}

	$TOTAL = sprint($EXVATTOT + $VAT + $taxext);
	$SUBTOT += $taxex;

/* --- ----------- Clac --------------------- */

	# insert Sales Order to DB
	$sql = "
		UPDATE sorders 
		SET cusnum = '$cusnum', deptname = '$dept[deptname]', deptid = '$dept[deptid]', cusacc = '$cust[accno]', 
			cusname = '$cust[cusname]', surname = '$cust[surname]', cusaddr = '$cust[addr1]', cusvatno = '$cust[vatnum]', 
			cordno = '$cordno', ordno = '$ordno', chrgvat = '$chrgvat', terms = '$terms', salespn = '$salespn', 
			fcid = '$cust[fcid]', currency = '$currs[symbol]', xrate = '$xrate', odate = '$odate', traddisc = '$traddisc', 
			delchrg = '$delchrg', subtot = '$SUBTOT', vat = '$VAT', total = '$TOTAL', balance = '$TOTAL', comm = '$comm', 
			location = '$cust[location]', discount = '$traddiscmt', delivery = '$delexvat' 
		WHERE sordid = '$sordid'";
	$rslt = db_exec($sql) or errDie("Unable to update Sales Order in Cubit.",SELF);

	# remove old data
	$sql = "DELETE FROM sord_data WHERE sordid='$sordid' AND div = '".USER_DIV."'";
	$rslt = db_exec($sql) or errDie("Unable to update Sales Order data in Cubit.",SELF);

	# pu in new data
	$sql = "
		INSERT INTO sord_data (
			sordid, dept, customer, addr1, div
		) VALUES (
			'$sordid', '$dept[deptname]', '$cust[cusname] $cust[surname]', '$cust[addr1]', '".USER_DIV."'
		)";
	$rslt = db_exec($sql) or errDie("Unable to insert Sales Order data to Cubit.",SELF);

# commit updating
pglib_transaction ("COMMIT") or errDie("Unable to commit a database transaction.",SELF);

/* --- Start button Listeners --- */
	if(isset($doneBtn)){

		# insert Sales Order to DB
		$sql = "UPDATE sorders SET done = 'y' WHERE sordid = '$sordid' AND div = '".USER_DIV."'";
		$rslt = db_exec($sql) or errDie("Unable to update Sales Order status in Cubit.",SELF);

		// Final Laytout
		$write = "
			<table ".TMPL_tblDflts.">
				<tr>
					<th>New International Sales Order</th>
				</tr>
				<tr bgcolor='".bgcolorg()."'>
					<td>Sales Order for customer <b>$cust[cusname] $cust[surname]</b> has been recorded.</td>
				</tr>
			</table>
			<p>
			<table ".TMPL_tblDflts.">
				<tr>
					<th>Quick Links</th>
				</tr>
				<script>document.write(getQuicklinkSpecial());</script>
			</table>";
		return $write;

	}elseif(isset($saveBtn)){

		// Final Laytout
		$write = "
			<table ".TMPL_tblDflts.">
				<tr>
					<th>New International Sales Order Saved</th>
				</tr>
				<tr bgcolor='".bgcolorg()."'>
					<td>Sales Order for customer <b>$cust[cusname] $cust[surname]</b> has been saved.</td>
				</tr>
			</table>
			<p>
			<table ".TMPL_tblDflts.">
				<tr>
					<th>Quick Links</th>
				</tr>
				<tr bgcolor='".bgcolorg()."'>
					<td><a href='sorder-view.php'>View Sales Orders</a></td>
				</tr>
				<script>document.write(getQuicklinkSpecial());</script>
			</table>";
		return $write;
	}else{
		if(isset($wtd)){$_POST['wtd']=$wtd;}
		return details($_POST);
	}

}


?>